﻿/*******************************************************************************
 * Copyright © 2016 李华丽 版权所有
 * Author: 李华丽
 * Description: 李华丽-快速开发平台
 * Website：http://www.cnblogs.com/lihuali
*********************************************************************************/
using System;
using System.Linq;
using System.Reflection;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;

namespace Wutos.Data
{
    //[DbConfigurationType(typeof(SQLiteConfiguration))]
    public class SQLiteDbContext : DbContext
    {
        private string fileName = $"{Environment.CurrentDirectory}/clock.db3";
        public SQLiteDbContext() : base()
        {
            Console.WriteLine($"【数据地址】{fileName}");
            if (File.Exists(fileName)==false)
            {
                throw new Exception($"{fileName}不存在");
            }
        }
        public SQLiteDbContext(string filename) : base()
        {
            this.fileName = filename;
        }
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            SqliteConnectionStringBuilder connectionStringBuilder = new SqliteConnectionStringBuilder();
            connectionStringBuilder.DataSource = fileName;
            connectionStringBuilder.ForeignKeys = true;

            SqliteConnection connection = new SqliteConnection();
            connection.ConnectionString = connectionStringBuilder.ConnectionString;
            options.UseSqlite(connection, XX);
        }
        private void XX(SqliteDbContextOptionsBuilder op)
        {
            
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            string assembleFileName = "";
            try
            {
                string currentAssembleFileName = Assembly.GetExecutingAssembly().Location.ToString();
                //Console.WriteLine("currentAssembleFileName:" + currentAssembleFileName);
                assembleFileName = currentAssembleFileName.Replace(".Data.", ".Mapping.").Replace("file:///", "");

                //Console.WriteLine(" pre assembleFileName Path: " + assembleFileName);

                if (assembleFileName.IndexOf(":") == -1)
                    assembleFileName = @"/" + assembleFileName;
                //Console.WriteLine("assembleFileName Path: " + assembleFileName);
                Assembly asm = Assembly.LoadFile(assembleFileName);
                var typesToRegister = asm.GetTypes()
                .Where(type => !String.IsNullOrEmpty(type.Namespace))
                .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
                foreach (var type in typesToRegister)
                {
                    object configurationInstance = Activator.CreateInstance(type);

                    modelBuilder.AddConfiguration(type, configurationInstance);
                }
                //modelBuilder.AddConfiguration(new UserMap());
                base.OnModelCreating(modelBuilder);
            }
            catch (Exception ex)
            {
#if DEBUG
                throw new Exception(ex.Message + "描述：" + assembleFileName);
#endif
            }
        }

        //public SQLiteDbContext(string filename) : base(new SQLiteConnection() {
        //    ConnectionString = new SQLiteConnectionStringBuilder() { DataSource = filename, ForeignKeys = true }.ConnectionString
        //},true)
        //{
        //    this.Configuration.AutoDetectChangesEnabled = false;//关闭自动跟踪对象的属性变化
        //    this.Configuration.ValidateOnSaveEnabled = false;//关闭保存时的实体验证
        //    this.Configuration.LazyLoadingEnabled = false;//关闭延迟加载
        //    this.Configuration.ProxyCreationEnabled = false;//关闭代理类
        //    this.Configuration.UseDatabaseNullSemantics = true; //关闭数据库null比较行为
        //}
    }
}
